<template>
    <div class="login">
        <h2>登录</h2>
        <form @submit.prevent="handleSubmit">
            <div>
                <label>用户名:</label>
                <input v-model="username" type="text" required>
            </div>
            <div>
                <label>密码:</label>
                <input v-model="password" type="password" required>
            </div>
            <button type="submit">登录</button>
            <p v-if="error" class="error">{{ error }}</p>
            <p>用户名：admin 密码：123456</p>
        </form>
    </div>
</template>

<script>
export default {
    data() {
        return {
            username: '',
            password: '',
            error: ''
        }
    },
    methods: {
        async handleSubmit() {
            try {
                const success = await this.$store.dispatch('login', {
                    username: this.username,
                    password: this.password
                })
                
                if (success) {
                    const redirect = this.$route.query.redirect || '/'
                    this.$router.push(redirect)
                } else {
                    this.error = '用户名或密码错误'
                }
            } catch (err) {
                this.error = '登录失败，请重试'
            }
        }
    }
}
</script>

<style scoped>
.login {
    max-width: 400px;
    margin: 0 auto;
    padding: 20px;
}
.error {
    color: red;
}
</style>